package frontend.pages.reports.commuter;

import backend.model.worklog.WorkLog;
import backend.service.worklog.WorkLogService;
import frontend.core.TimeTrackingWebApplication;
import frontend.model.reports.CommutersReportEntry;
import frontend.model.reports.ReportInputUIModel;
import frontend.pages.reports.base.AbstractReportForm;
import org.apache.wicket.markup.html.WebMarkupContainer;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

public class CommutersReportForm extends AbstractReportForm<CommutersReportEntry> {

    public CommutersReportForm(String id, ReportInputUIModel model, List<CommutersReportEntry> reportResults, WebMarkupContainer reportResultsContainer) {
        super(id, model, reportResults, reportResultsContainer);
    }

    @Override
    protected void addAdditionalFilteringComponents() {
        // No other components
    }

    @Override
    protected List<CommutersReportEntry> retrieveReportDataFromDatabase() {
        List<CommutersReportEntry> reportEntryList = new LinkedList<>();

        WorkLogService workLogService = TimeTrackingWebApplication.getService(WorkLogService.class);
        List<WorkLog> workLogs =  workLogService.loadWorkLogOfCommutersForTimeInterval(uiModel.getStartDate(), uiModel.getEndDate());
        Map<Integer, List<WorkLog>> employeeIdToWorkLogsMap = new HashMap<>();
        for (WorkLog workLog : workLogs) {
            if (employeeIdToWorkLogsMap.get(workLog.getEmployee().getId()) == null) {
                employeeIdToWorkLogsMap.put(workLog.getEmployee().getId(), new LinkedList<WorkLog>());
            }
            employeeIdToWorkLogsMap.get(workLog.getEmployee().getId()).add(workLog);
        }
        for (List<WorkLog> workLogList : employeeIdToWorkLogsMap.values()) {
            reportEntryList.add(new CommutersReportEntry(workLogList));
        }

        return reportEntryList;
    }
}
